/**
 * 流程引擎
 * 处理需求流程逻辑
 */
class WorkflowEngine {
    constructor() {
        this.workflows = {};
        this.demandTypes = {};
    }
    
    /**
     * 初始化流程引擎
     */
    async initialize() {
        try {
            this.workflows = await window.dataManager.getWorkflows();
            this.demandTypes = await window.dataManager.getDemandTypes();
            return true;
        } catch (error) {
            console.error('流程引擎初始化失败:', error);
            return false;
        }
    }
    
    /**
     * 根据需求类型获取流程模板
     */
    getWorkflowTemplate(demandType) {
        const typeConfig = this.demandTypes[demandType];
        if (!typeConfig || !typeConfig.workflowTemplate) {
            return null;
        }
        
        return this.workflows[typeConfig.workflowTemplate] || null;
    }
    
    /**
     * 创建需求流程
     */
    createWorkflow(demandType, demandId) {
        const template = this.getWorkflowTemplate(demandType);
        if (!template) {
            throw new Error(`未找到需求类型 ${demandType} 的流程模板`);
        }
        
        const workflow = {
            id: `workflow_${demandId}`,
            demandId: demandId,
            templateId: template.id,
            templateName: template.name,
            status: 'active',
            currentNodeIndex: 0,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
            nodes: template.nodes.map((node, index) => ({
                ...node,
                status: index === 0 ? 'active' : 'pending',
                startedAt: index === 0 ? new Date().toISOString() : null,
                completedAt: null,
                completedBy: null,
                comments: [],
                addedManually: false
            }))
        };
        
        return workflow;
    }
    
    /**
     * 确认当前节点
     */
    confirmCurrentNode(workflow, userId, comment = '') {
        const currentNode = workflow.nodes[workflow.currentNodeIndex];
        
        if (!currentNode || currentNode.status !== 'active') {
            throw new Error('当前节点不可确认');
        }
        
        // 更新当前节点状态
        currentNode.status = 'completed';
        currentNode.completedAt = new Date().toISOString();
        currentNode.completedBy = userId;
        
        if (comment) {
            currentNode.comments.push({
                userId: userId,
                comment: comment,
                timestamp: new Date().toISOString(),
                type: 'confirm'
            });
        }
        
        // 移动到下一个节点
        const nextNodeIndex = workflow.currentNodeIndex + 1;
        
        if (nextNodeIndex < workflow.nodes.length) {
            workflow.currentNodeIndex = nextNodeIndex;
            workflow.nodes[nextNodeIndex].status = 'active';
            workflow.nodes[nextNodeIndex].startedAt = new Date().toISOString();
        } else {
            // 所有节点完成，但需要手动标记完成
            workflow.status = 'awaiting_completion';
        }
        
        workflow.updatedAt = new Date().toISOString();
        
        return workflow;
    }
    
    /**
     * 手动加签节点
     */
    addSignNode(workflow, afterNodeIndex, newNode, userId) {
        if (afterNodeIndex < 0 || afterNodeIndex >= workflow.nodes.length) {
            throw new Error('无效的节点位置');
        }
        
        const signNode = {
            id: `sign_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            name: newNode.name,
            description: newNode.description || '',
            defaultAssignee: newNode.assignee,
            status: 'pending',
            addedManually: true,
            addedBy: userId,
            addedAt: new Date().toISOString(),
            order: workflow.nodes[afterNodeIndex].order + 0.5,
            requiredFields: newNode.requiredFields || [],
            allowedActions: newNode.allowedActions || ['confirm'],
            comments: []
        };
        
        // 插入新节点
        workflow.nodes.splice(afterNodeIndex + 1, 0, signNode);
        
        // 更新后续节点的索引
        if (workflow.currentNodeIndex > afterNodeIndex) {
            workflow.currentNodeIndex++;
        }
        
        workflow.updatedAt = new Date().toISOString();
        
        return workflow;
    }
    
    /**
     * 标记流程完成
     */
    markWorkflowComplete(workflow, userId, comment = '') {
        if (workflow.status === 'completed') {
            throw new Error('流程已经完成');
        }
        
        // 检查是否所有节点都已完成
        const allNodesCompleted = workflow.nodes.every(node => node.status === 'completed');
        
        if (!allNodesCompleted) {
            throw new Error('还有未完成的节点，无法标记完成');
        }
        
        workflow.status = 'completed';
        workflow.completedAt = new Date().toISOString();
        workflow.completedBy = userId;
        workflow.updatedAt = new Date().toISOString();
        
        if (comment) {
            workflow.completionComment = {
                userId: userId,
                comment: comment,
                timestamp: new Date().toISOString()
            };
        }
        
        return workflow;
    }
    
    /**
     * 回退流程到指定节点
     */
    rollbackToNode(workflow, nodeIndex, userId, reason = '') {
        if (nodeIndex < 0 || nodeIndex >= workflow.nodes.length) {
            throw new Error('无效的节点索引');
        }
        
        if (nodeIndex >= workflow.currentNodeIndex) {
            throw new Error('只能回退到之前的节点');
        }
        
        // 重置后续节点状态
        for (let i = nodeIndex + 1; i < workflow.nodes.length; i++) {
            const node = workflow.nodes[i];
            node.status = 'pending';
            node.startedAt = null;
            node.completedAt = null;
            node.completedBy = null;
            
            // 添加回退记录
            node.comments.push({
                userId: userId,
                comment: `流程回退: ${reason}`,
                timestamp: new Date().toISOString(),
                type: 'rollback'
            });
        }
        
        // 设置当前节点
        workflow.currentNodeIndex = nodeIndex;
        workflow.nodes[nodeIndex].status = 'active';
        workflow.nodes[nodeIndex].startedAt = new Date().toISOString();
        workflow.status = 'active';
        workflow.updatedAt = new Date().toISOString();
        
        return workflow;
    }
    
    /**
     * 获取流程进度百分比
     */
    getWorkflowProgress(workflow) {
        if (!workflow || !workflow.nodes || workflow.nodes.length === 0) {
            return 0;
        }
        
        const completedNodes = workflow.nodes.filter(node => node.status === 'completed').length;
        return Math.round((completedNodes / workflow.nodes.length) * 100);
    }
    
    /**
     * 获取当前节点信息
     */
    getCurrentNode(workflow) {
        if (!workflow || !workflow.nodes || workflow.currentNodeIndex >= workflow.nodes.length) {
            return null;
        }
        
        return workflow.nodes[workflow.currentNodeIndex];
    }
    
    /**
     * 获取下一个节点信息
     */
    getNextNode(workflow) {
        if (!workflow || !workflow.nodes) {
            return null;
        }
        
        const nextIndex = workflow.currentNodeIndex + 1;
        if (nextIndex >= workflow.nodes.length) {
            return null;
        }
        
        return workflow.nodes[nextIndex];
    }
    
    /**
     * 检查用户是否可以操作当前节点
     */
    canUserOperateCurrentNode(workflow, userId) {
        const currentNode = this.getCurrentNode(workflow);
        if (!currentNode) {
            return false;
        }
        
        // 检查是否是指定的负责人
        if (currentNode.defaultAssignee && currentNode.defaultAssignee !== userId) {
            return false;
        }
        
        // 检查节点状态
        return currentNode.status === 'active';
    }
    
    /**
     * 获取流程统计信息
     */
    getWorkflowStats(workflow) {
        if (!workflow || !workflow.nodes) {
            return {
                totalNodes: 0,
                completedNodes: 0,
                pendingNodes: 0,
                activeNodes: 0,
                progress: 0
            };
        }
        
        const stats = {
            totalNodes: workflow.nodes.length,
            completedNodes: workflow.nodes.filter(n => n.status === 'completed').length,
            pendingNodes: workflow.nodes.filter(n => n.status === 'pending').length,
            activeNodes: workflow.nodes.filter(n => n.status === 'active').length,
            progress: this.getWorkflowProgress(workflow)
        };
        
        return stats;
    }
    
    /**
     * 验证流程配置
     */
    validateWorkflowTemplate(template) {
        const errors = [];
        
        if (!template.id) {
            errors.push('流程ID不能为空');
        }
        
        if (!template.name) {
            errors.push('流程名称不能为空');
        }
        
        if (!template.nodes || !Array.isArray(template.nodes) || template.nodes.length === 0) {
            errors.push('流程必须包含至少一个节点');
        } else {
            template.nodes.forEach((node, index) => {
                if (!node.id) {
                    errors.push(`节点 ${index + 1} 缺少ID`);
                }
                
                if (!node.name) {
                    errors.push(`节点 ${index + 1} 缺少名称`);
                }
                
                if (typeof node.order !== 'number') {
                    errors.push(`节点 ${index + 1} 缺少有效的顺序号`);
                }
            });
            
            // 检查节点ID是否重复
            const nodeIds = template.nodes.map(n => n.id);
            const uniqueIds = [...new Set(nodeIds)];
            if (nodeIds.length !== uniqueIds.length) {
                errors.push('存在重复的节点ID');
            }
        }
        
        return {
            valid: errors.length === 0,
            errors
        };
    }
    
    /**
     * 克隆流程模板
     */
    cloneWorkflowTemplate(templateId, newId, newName) {
        const template = this.workflows[templateId];
        if (!template) {
            throw new Error('源流程模板不存在');
        }
        
        const cloned = JSON.parse(JSON.stringify(template));
        cloned.id = newId;
        cloned.name = newName;
        cloned.description = `基于 ${template.name} 克隆`;
        
        return cloned;
    }
    
    /**
     * 获取流程时间线
     */
    getWorkflowTimeline(workflow) {
        const timeline = [];
        
        // 流程创建
        timeline.push({
            type: 'created',
            timestamp: workflow.createdAt,
            title: '流程创建',
            description: `创建了 ${workflow.templateName} 流程`
        });
        
        // 节点事件
        workflow.nodes.forEach(node => {
            if (node.startedAt) {
                timeline.push({
                    type: 'node_started',
                    timestamp: node.startedAt,
                    title: `开始 ${node.name}`,
                    description: node.description,
                    nodeId: node.id
                });
            }
            
            if (node.completedAt) {
                timeline.push({
                    type: 'node_completed',
                    timestamp: node.completedAt,
                    title: `完成 ${node.name}`,
                    description: `由 ${node.completedBy} 完成`,
                    nodeId: node.id
                });
            }
            
            // 节点评论
            node.comments.forEach(comment => {
                timeline.push({
                    type: 'comment',
                    timestamp: comment.timestamp,
                    title: comment.type === 'rollback' ? '流程回退' : '添加评论',
                    description: comment.comment,
                    userId: comment.userId,
                    nodeId: node.id
                });
            });
        });
        
        // 流程完成
        if (workflow.completedAt) {
            timeline.push({
                type: 'completed',
                timestamp: workflow.completedAt,
                title: '流程完成',
                description: `由 ${workflow.completedBy} 标记完成`
            });
        }
        
        // 按时间排序
        timeline.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
        
        return timeline;
    }
}

// 创建全局实例
window.workflowEngine = new WorkflowEngine();